import { reqgetcoupon } from "../../http/api";

//初始值
const initState = {
  list1: [],
  list2: [],
  list3: [],
};

//types
const TYPES = {
  COUPON_CHANGE_LIST1: "COUPON_CHANGE_LIST1",
  COUPON_CHANGE_LIST2: "COUPON_CHANGE_LIST2",
  COUPON_CHANGE_LIST3: "COUPON_CHANGE_LIST3",
};

//修改state的reducer
const reducer = (state = initState, action) => {
  switch (action.type) {
    case TYPES.COUPON_CHANGE_LIST1:
      return {
        ...state,
        list1: action.list1,
      };
    case TYPES.COUPON_CHANGE_LIST2:
      return {
        ...state,
        list2: action.list2,
      };
    case TYPES.COUPON_CHANGE_LIST3:
      return {
        ...state,
        list3: action.list3,
      };
    default:
      return state;
  }
};

//actionCreators
export const actions = {
  changeList1: (list1) => ({
    type: TYPES.COUPON_CHANGE_LIST1,
    list1,
  }),
  changeList2: (list2) => ({
    type: TYPES.COUPON_CHANGE_LIST2,
    list2,
  }),
  changeList3: (list3) => ({
    type: TYPES.COUPON_CHANGE_LIST3,
    list3,
  }),

  //请求优惠券数据
  reqCoupon: () => {
    return (dispatch, getState) => {
      reqgetcoupon().then((res) => {
        if (res.data.code == 200) {
          dispatch(actions.changeList1(res.data.list[0].content));
          dispatch(actions.changeList2(res.data.list[1].content));
          dispatch(actions.changeList3(res.data.list[2].content));
        }
      });
    };
  },
  //获取时间
  getTime: (time) => {
    return (dispatch, getState) => {
      let date = new Date(Number(time));
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let date2 = date.getDate();
      return year + "-" + month + "-" + date2;
    };
  },
};

//导出数据
export const getList1 = (state) => state.coupon.list1;
export const getList2 = (state) => state.coupon.list2;
export const getList3 = (state) => state.coupon.list3;

//导出reducer
export default reducer;
